
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ModelViewSet
from goods.models import SKU
from meiduo_admin.serializers.sku_serializers import *
from meiduo_admin.custom_paginations import MyPage
from goods.models import GoodsCategory


# 定义获取规格选项信息的接口视图
class SpecOptView(ListAPIView):
    queryset = SPUSpecification.objects.all()
    serializer_class = SPUSpecModerSerializer

    def get_queryset(self):
        # 根据前端路径中pk，过滤出规格数据返回
        # self.kwargs是一个字典，用来保存路径中命名分组参数的！
        spu_id = self.kwargs.get('pk')
        return self.queryset.filter(spu_id=spu_id)



# 定义获取可选spu信息的接口视图
class SPUSimpleView(ListAPIView):
    queryset = SPU.objects.all()
    serializer_class = SPUSimpleModelSerializer


# 定义获取三级分类接口视图类
class GoodsCategoryView(ListAPIView):
    queryset = GoodsCategory.objects.all()
    serializer_class = GoodsCategoryModelSerializer

    # 处理的分类模型类数据是三级分类数据
    def get_queryset(self):
        return self.queryset.filter(
            parent_id__gt=37 # 大于37过滤出来的就是三级分类对象
        )


# 定义sku表管理视图
class SKUViewSet(ModelViewSet):
    queryset = SKU.objects.all()
    serializer_class = SKUModelSerializer

    pagination_class = MyPage

    # 重写该函数实现过滤
    def get_queryset(self):
        keyword =self.request.query_params.get('keyword')
        if keyword:
            return self.queryset.filter(name__contains=keyword)
        return self.queryset.all() # .all()确保是最新mysql数据